package com.example.NetworkSender;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import com.example.NetworkSender.ui.ReceiveListener;
import com.example.NetworkSender.ui.SendListener;

public class MainActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addExceptionHandler();

        setContentView(R.layout.main);

        Engine engine = new Engine(References.DEFAULT_PORT);
        EditText input = (EditText) findViewById(R.id.tbInput);
        TextView output = (TextView) findViewById(R.id.tbOutput);
        EditText tbAddress = (EditText) findViewById(R.id.tbAddress);


        SendListener sendListener = new SendListener(engine, input, tbAddress);
        ReceiveListener receiveListener = new ReceiveListener(engine, output);

        findViewById(R.id.buttonSend).setOnClickListener(sendListener);
        findViewById(R.id.buttonReceive).setOnClickListener(receiveListener);
    }

    private void addExceptionHandler() {
        final Thread.UncaughtExceptionHandler oldHandler =
                Thread.getDefaultUncaughtExceptionHandler();

        Thread.setDefaultUncaughtExceptionHandler(
                new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(
                            Thread paramThread,
                            Throwable paramThrowable
                    ) {
                        Log.e("something is wrong", paramThrowable.getMessage());
                        StackTraceElement[] stk = paramThrowable.getStackTrace();
                        for (StackTraceElement traceElement : stk) {
                            Log.e("something is wrong", traceElement.getMethodName() + " " + "line# " + traceElement.getLineNumber());
                        }
                        ;

                        if (oldHandler != null)
                            oldHandler.uncaughtException(
                                    paramThread,
                                    paramThrowable
                            ); //Delegates to Android's error handling
                        else
                            System.exit(2); //Prevents the service/app from freezing
                    }
                });
    }
}
